const router = require('koa-router')()
const validationMiddleware = require('../validate/validate');
const { user } = require("../models/user")
const Joi = require('joi');
const response = require("../utils/response");
const { dealNotEmpty, dealNotEmptyArry, handleDatabaseError } = require("../utils/dberrordeal");
const { encrypt, decrypt } = require('../utils/encode')
const { sign, verify } = require('../utils/auth')
const rulesSchema = {
  '/register': Joi.object({
    email: dealNotEmpty('邮箱'),
    password: dealNotEmpty('密码'),
  }),
  '/login': Joi.object({
    email: dealNotEmpty('邮箱'),
    password: dealNotEmpty('密码'),
  }),
};
router.post('/register', validationMiddleware(rulesSchema), async (ctx, next) => {
  const data = ctx.request.body
  await user.findOne({ email: data.email }).then(async res => {
    if (res) {
      response.error(ctx, { message: '用户已存在' });
    } else {
      data.password = encrypt(data.password)
      data.userName= Math.random().toString(36).substring(2)
      let fres = await user.create(data)
      if (fres) {
        response.success(ctx, { message: '注册成功' });
      }
    }
  })
})
router.post('/login', validationMiddleware(rulesSchema), async (ctx, next) => {
  const data = ctx.request.body
  await user.findOne({ email: data.email }).then(async res => {
    if (res) {

      if (data.password === decrypt(res.password)) {
        let token = sign({
          email: res.email,
          id: res._id,
          // time: Date.now()
        })
        response.success(ctx, { message: '登录成功', data: { token: token, userinfo: res } });
      }
    } else {
      response.error(ctx, { message: '请先注册' });
    }
  })
})

module.exports = router
